﻿using MobaCommon.Dto;
using MOBAServer.Room;
using System;
using System.Collections.Generic;
using System.Text;

namespace MOBAServer.Cache
{
    public class FightCache:RoomCacheBase<FightRoom>
    {
        private int id;
        /// <summary>
        /// 
        /// </summary>
        public void StartFight(List<SelectModel> team1, List<SelectModel> team2)
        {
            FightRoom room = null;
            //检测有没有可重用的房间
            if(!roomQue.TryDequeue(out room))
            {
                room = new FightRoom(id++,team1.Count+team2.Count);
            }
            //初始化房间数据
            room.Init(team1,team2);
            foreach (var item in team1)
            {
                playerRoomDic.TryAdd(item.playerId,room.id);
            }
            foreach (var item in team2)
            {
                playerRoomDic.TryAdd(item.playerId, room.id);
            }
            idRoomDic.TryAdd(room.id,room);
            //所有的玩家都进入之后 才发送
        }
        /// <summary>
        /// 进入战斗
        /// </summary>
        /// <returns></returns>
        public FightRoom Enter(int playerId,MobaClient client)
        {
            FightRoom room = GetRoom(playerId);

            room.Enter(client);
            return room;
        }
        /// <summary>
        /// 获取房间
        /// </summary>
        /// <param name="playerId"></param>
        /// <returns></returns>
        public FightRoom GetRoom(int playerId)
        {
            int roomId = -1;
            if (!playerRoomDic.TryGetValue(playerId, out roomId))
                return null;
            FightRoom room = null;
            if (!idRoomDic.TryGetValue(roomId, out room))
                return null;
            return room;
        }

        /// <summary>
        /// 玩家下线处理
        /// </summary>
        /// <param name="client"></param>
        /// <param name="playerId"></param>
        public void Offline(MobaClient client,int playerId)
        {
            FightRoom room = GetRoom(playerId);

            room.Leave(client);

            //判断房间内还有没有人 没有人就销毁
            if(room.IsAllLeave)
            {
                Destroy(room.id);
            }

        }

        private void Destroy(int roomId)
        {
            FightRoom room = null;
            if (!idRoomDic.TryRemove(roomId, out room))
                return;
            //移除玩家ID和房间ID的关系
            foreach (var item in room.Heros)
            {
                playerRoomDic.TryRemove(item.Id, out roomId);
            }

            //清空房间内的数据
            room.ClearData();
            //入队列
            roomQue.Enqueue(room);
        }
    }
}
